import { listMoment, removeMoment } from '@/services/api/moment';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import '@umijs/max';
import { message, Popconfirm } from 'antd';
import React, { useRef } from 'react';

const TableList: React.FC = () => {
  const actionRef = useRef<ActionType>();

  /**
   * @param id
   * 根据id删除动态
   */
  const handleRemove = async (id: any) => {
    const hide = message.loading('正在删除');
    try {
      await removeMoment(id);
      hide();
      message.success('删除成功，将很快刷新');
      actionRef.current?.reload(); // 刷新表格
      return true;
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  // 表格列 标题配置
  const columns: ProColumns<any>[] = [
    {
      title: '创建人',
      dataIndex: 'user_name',
      valueType: 'text',
    },
    {
      title: '内容',
      dataIndex: 'content',
      valueType: 'textarea',
      width: 500,
      // ellipsis: true,
      hideInSearch: true,
      copyable: true,
    },
    {
      title: '点赞数',
      dataIndex: 'commentCount',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '评论数',
      dataIndex: 'commentCount',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '收藏数',
      dataIndex: 'tagCount',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '更新时间',
      sorter: true,
      dataIndex: 'updateAt',
      valueType: 'dateTime',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <Popconfirm
          key="del"
          title="确认删除这条动态吗?"
          onConfirm={() => handleRemove(record.id)}
          okText="确认"
          cancelText="取消"
        >
          <a>删除</a>
        </Popconfirm>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        headerTitle={'动态列表'}
        actionRef={actionRef}
        request={async (params, sort, filter) => {
          const {data, code} = await listMoment(params)
          return {
            success: code === 0,
            data: data?.records || [],
            total: Number(data?.total) || 0
          }

        }}
        columns={columns}
        rowKey="key"
        search={{
          labelWidth: 'auto',
        }}
        pagination={{
          pageSize: 10,
          onChange: (page) => console.log(page),
        }}
      />
    </PageContainer>
  );
};
export default TableList;
